package team.kirohuji.service.impl.user;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import team.kirohuji.domain.user.Priority;
import team.kirohuji.repository.jpa.user.PriorityRepository;
import team.kirohuji.service.user.PriorityService;
import team.kirohuji.service.user.UserService;

/**
 * 权限服务实现类
 * 
 * @author kirohuji
 *
 */
@Service("priorityService")
public class PriorityServiceImpl implements PriorityService {

	@Autowired
	private PriorityRepository priorityRepository;
	@Autowired
	private UserService userService;

	@Override
	public List<Priority> findAll() {
		return priorityRepository.findAll();
	}

	@Override
	public List<Priority> queryListParentId(Integer parentId, Integer priorityType, List<Integer> menuIdList) {
		List<Priority> menuList = priorityRepository.queryListParentId(parentId, priorityType);
		if (menuIdList == null) {
			return menuList;
		}
		List<Priority> userMenuList = new ArrayList<>();
		for (Priority menu : menuList) {
			if (menuIdList.contains(menu.getPriorityId())) {
				userMenuList.add(menu);
			}
		}
		return userMenuList;
	}

	@Override
	public List<Priority> queryNotButtonList() {
		return priorityRepository.queryNotButtonList();
	}

	@Override
	public List<Priority> getUserMenuList(Integer userId, Integer priorityType) {
		// 获取用户权限菜单
		List<Integer> menuIdList = userService.queryAllMenuId(userId);
		return getAllMenuList(menuIdList, priorityType);
	}

	@Override
	public List<Priority> getMenuTreeList(List<Priority> menuList, Integer priorityType, List<Integer> menuIdList) {
		List<Priority> subMenuList = new ArrayList<Priority>();
		for (Priority entity : menuList) {
			if (entity.getNodeType() == MenuType.CATALOG.getValue()) {// 目录
				entity.setList(getMenuTreeList(queryListParentId(entity.getPriorityId(), priorityType, menuIdList),
						priorityType, menuIdList));
			}
			subMenuList.add(entity);
		}
		return subMenuList;
	}

	@Override
	public List<Priority> getAllMenuList(List<Integer> menuIdList, Integer priorityType) {
		// 查询根菜单列表
		List<Priority> menuList = queryListParentId(0, priorityType, menuIdList);
		// 递归获取子菜单
		getMenuTreeList(menuList, priorityType, menuIdList);

		return menuList;
	}

	@Override
	public List<Priority> queryPriorityByPriorityType(String priorityType) {
		return priorityRepository.queryPriorityByPriorityType(priorityType);
	}

	@Override
	public List<Priority> queryParentPriority() {
		return priorityRepository.queryParentPriority();
	}

}
